package com.jianjun.framework.security.service;

import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Inject;
import com.jfinal.i18n.I18n;
import com.jfinal.kit.ThreadPoolKit;
import com.jianjun.common.constant.Constants;
import com.jianjun.common.constant.UserConstants;
import com.jianjun.common.util.SecurityUtils;
import com.jianjun.framework.manager.factory.AsyncFactory;
import com.jianjun.framework.security.RegisterBody;
import com.jianjun.project.common.model.SysUser;
import com.jianjun.project.system.config.SysConfigService;
import com.jianjun.project.system.login.SysLoginService;
import com.jianjun.project.system.user.SysUserService;


/**
 *
 * @author source
 * {@code @date} 2025/1/23 13:37
 */
public class SysRegisterService {
    @Inject
    SysUserService userService;
    @Inject
    SysConfigService configService;
    @Inject
    SysLoginService loginService;

    public String register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            loginService.validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StrUtil.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StrUtil.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (!userService.checkUserNameUnique(sysUser)) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, I18n.use().format("user.register.success")));
            }
        }
        return msg;
    }
}
